package com.tang.module.system.service.impl;

import cn.hutool.core.convert.Convert;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.tang.module.system.mapper.InterfaceLimitMapper;
import com.tang.module.system.entity.InterfaceLimit;
import com.tang.module.system.service.InterfaceLimitService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.support.TransactionTemplate;

import java.util.List;
import java.util.stream.Collectors;

/**
 * 接口访问次数
(InterfaceLimit)表服务实现类
 *
 * @author tang
 * @since 2022-01-21 16:28:34
 */
@Service("interfaceLimitService")
public class InterfaceLimitServiceImpl extends ServiceImpl<InterfaceLimitMapper, InterfaceLimit> implements InterfaceLimitService {

    @Autowired
    private InterfaceLimitMapper interfaceLimitMapper;

    @Autowired
    private TransactionTemplate transactionTemplate;


    @Override
    public Boolean empty(String userAccount, String interfaceType) {
        return interfaceLimitMapper.update(null, Wrappers.<InterfaceLimit>lambdaUpdate()
                .set(InterfaceLimit::getRemainingTimes,0)
                .eq(InterfaceLimit::getUserAccount,userAccount)
                .eq(InterfaceLimit::getInterfaceType,interfaceType)) == 1;
    }

    @Override
    public Boolean initNumber() {
        //全部未新增的用户和对应的类型
        List<InterfaceLimit> notInit = interfaceLimitMapper.getNotInit();
        //填充数据
        List<InterfaceLimit> limitList = notInit.parallelStream().peek(interfaceLimit -> {
            //访问次数初始值
            interfaceLimit.setRemainingTimes(0L);
            interfaceLimit.setToAccess(0L);
        }).collect(Collectors.toList());
        //在编程事务中执行
        return transactionTemplate.execute((status) ->{
            for (InterfaceLimit interfaceLimit : limitList) {
                interfaceLimitMapper.insert(interfaceLimit);
            }
            return Boolean.TRUE;
        });
    }

    @Override
    public Boolean addNumber(String userAccount, Long number,String interfaceType) {
        interfaceLimitMapper.addNumber(userAccount, number,interfaceType);
        return Boolean.TRUE;
    }
}
